<template>
    <!-- index.wxml -->
    <view class="container">
        <view class="userinfo">
            <button v-if="!hasUserInfo && canIUse" open-type="getUserInfo" @getuserinfo="getUserInfo">获取头像昵称</button>
            <block v-else>
                <image @tap="bindViewTap" class="userinfo-avatar" :src="userInfo.avatarUrl" mode="cover"></image>
                <text class="userinfo-nickname">{{ userInfo.nickName }}</text>
            </block>
        </view>
        <view class="usermotto">
            <button type="primary" @tap="handleToCanvas">{{ motto }}</button>
        </view>
    </view>
</template>

<script>
//index.js
//获取应用实例
const app = getApp();
export default {
    data() {
        return {
            motto: '点我开始签名',
            userInfo: {
                avatarUrl: '',
                nickName: ''
            },
            hasUserInfo: false,
            canIUse: uni.canIUse('button.open-type.getUserInfo')
        };
    },
    onLoad: function () {
        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            });
        } else {
            if (this.canIUse) {
                // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                // 所以此处加入 callback 以防止这种情况
                app.globalData.userInfoReadyCallback = (res) => {
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    });
                };
            } else {
                // 在没有 open-type=getUserInfo 版本的兼容处理
                uni.getUserInfo({
                    success: (res) => {
                        app.globalData.userInfo = res.userInfo;
                        this.setData({
                            userInfo: res.userInfo,
                            hasUserInfo: true
                        });
                    }
                });
            }
        }
    },
    methods: {
        //事件处理函数
        bindViewTap: function () {
            uni.navigateTo({
                url: '../logs/logs'
            });
        },

        handleToCanvas: function () {
            uni.navigateTo({
                url: '../canvas/canvas'
            });
        },

        getUserInfo: function (e) {
            console.log(e);
            app.globalData.userInfo = e.detail.userInfo;
            this.setData({
                userInfo: e.detail.userInfo,
                hasUserInfo: true
            });
        }
    }
};
</script>
<style>
@import './index.css';
</style>
